<template>
    <div>
        <!-- 初始化界面 -->
        <TopFilter
                :list="topFilterList"
                @filterChange="changeHandle" ></TopFilter>
        <FilterTable
            ref="table"
            :columns="columns"
            :fetchapi="fetchApi"
            :params="fetchParams"
            :isSelectColumn="false"
            :isConfigPageSize="50"
            :datakey="'records'"
            columnsRef="userManage"
            :onCellChange="onCellChange"
            :onColumnsChange="(columns) => (this.columns = columns)"
        >
        </FilterTable>
        <Drawer
                :visible.sync="addVisible"
                title="添加备件分类"
                :width="900"
                destroyOnClose
                :containerStyle="{  height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '24px' }">
            <addForm  @close="closeaddHandler"/>
        </Drawer>
        <Drawer
                :visible.sync="editVisible"
                title="备件物料组"
                :width="900"
                destroyOnClose
                :containerStyle="{  height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '24px' }">
            <addForm :rowData="formdata" @close="closeEditHandler"/>
        </Drawer>
    </div>
</template>

<script>
import { getPartTypeBaseInfoPage ,managerStatus,updateOrderTypeController} from '@/api/partsmanage/partTypeManage/query';
import { dictionary } from '@/utils/dictMixin';
import {timeHourAndMin} from '@/utils/validate.js';
import AddForm from './addForm';
export default {
  name: 'partTypeBase',
  components: { AddForm},
  mixins: [dictionary],
  data() {
    return {
      formdata: null,
      editVisible: false,
      addVisible: false,
      dialogWidth: '920px',
      attVisible: false,
      dialog: {
        title: '新增',
        component: null,
        visible: false,
        width: '',
        initData: null,
        showType: 'add',
      },
      title: '',
      topFilterList: this.createTopFilterList(),
      visible: false,
      fetchApi: getPartTypeBaseInfoPage,
      fetchParams: {
        xhrAbort: true,
        code: '',
        partTypeName: '',
      },
      columns: this.createTableColumns(),
      userId: '',
      smsTypeShow: false,
      userNum: '',
      userName: '',
      isDisabled: false,
    };
  },
  mounted() {
    // 分页
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    closeEditHandler() {
      this.editVisible = false;
      this.fetchParams = Object.assign({}, this.fetchParams, { xhrAbort: false });
    },
    closeaddHandler() {
      this.addVisible = false;
      this.fetchParams = Object.assign({}, this.fetchParams, { xhrAbort: false });
    },
    closeHandlerAttrMain(val, type) {
      this.attVisible = val;
      if (type == 'refresh') {
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeExportHandler(){
      this.attVisible = false;
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          fixed: 'left',
          render: (props) => {
            return (
              <div>
                <el-button size = "mini" type = "text" onClick = {() => this.edit(props.row, { title: '修改', Type: 'edit' })}>
               明细
                </el-button>
              </div>
            );
          },
        },
        {
          title: '订单类型',
          dataIndex: 'xsddlx',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.xsddlx, '3003')}</span>;
          }
        },
        {
          title: '最低起订金额',
          dataIndex: 'pjlxje',
          editable: true,
          defaultEditable: true,
          editRequired: true,
          editType: 'number',
          // editValidator:(rule, value, callback) => {
          //   var discountRate = parseInt(value.pjlxje);
          //   var tableParams = this.$refs.table.$refs.pageTable;
          //
          //
          //   console.log("修改开始");
          //   console.log(discountRate)
          //   console.log(tableParams.pjlxje)
          //   if (discountRate === undefined || discountRate === '' || discountRate === null) {
          //     callback(new Error('值不能为空'));
          //   }
          //   var g = /^\-?[0-9]\d*.?\d*$/;
          //   if (g.test(discountRate)) {
          //     if (100 >= discountRate > 0) {
          //       callback();
          //       editPartReturnParam(value).then(res =>{
          //         this.$notify.success({title: '提示信息',message:'修改成功!'});
          //       }).catch(err =>{
          //         this.$notify.error({title: '提示信息',message:err.errMsg||'修改失败!'});
          //       })
          //       return;
          //     }
          //   }
          //   callback(new Error('只能输入数字，且在0-100之间'));
          // },
        },
      {
        title: '免运费次数',
        dataIndex: 'pjlxcs',
        editable: true,
        defaultEditable: true,
        editRequired: true,
        editType: 'number',
        // editValidator:(rule, value, callback) => {
        //   var discountRate = parseInt(value.pjlxcs);
        //  var tableParams = this.$refs.table.$refs.pageTable;
        //   if (discountRate === undefined || discountRate === '' || discountRate === null) {
        //     callback(new Error('值不能为空'));
        //   }
        //   var g = /^\-?[0-9]\d*.?\d*$/;
        //   if (g.test(discountRate)) {
        //     if (100 >= discountRate > 0) {
        //       callback();
        //       editPartReturnParam(value).then(res =>{
        //         this.$notify.success({title: '提示信息',message:'修改成功!'});
        //       }).catch(err =>{
        //         this.$notify.error({title: '提示信息',message:err.errMsg||'修改失败!'});
        //       })
        //       return;
        //     }
        //   }
        //   callback(new Error('只能输入数字，且在0-100之间'));
        // },
      },
      {
        title: '订单每天截止时间',
        dataIndex: 'orderLimitTime',
        dateFormat: 'yyyy-MM-dd',
        editable: true,
        defaultEditable: true,
        editRequired: true,
        editType: 'input',
        rules: [
          { validator: timeHourAndMin, trigger: 'blur'}
        ],
        // editValidator:(rule, value, callback) => {
        //   var discountRate = parseInt(value.orderLimitTime);
        //   var tableParams = this.$refs.table.$refs.pageTable;
        //   if (discountRate === undefined || discountRate === '' || discountRate === null) {
        //     callback(new Error('值不能为空'));
        //   }
        //   var g = /^\-?[0-9]\d*.?\d*$/;
        //   if (g.test(discountRate)) {
        //     if (100 >= discountRate > 0) {
        //       callback();
        //       editPartReturnParam(value).then(res =>{
        //         this.$notify.success({title: '提示信息',message:'修改成功!'});
        //       }).catch(err =>{
        //         this.$notify.error({title: '提示信息',message:err.errMsg||'修改失败!'});
        //       })
        //       return;
        //     }
        //   }
        //   callback(new Error('只能输入数字，且在0-100之间'));
        // },
      },
      {
        title: '超过次数是否可提报',
        dataIndex: 'isLimitNum',
        render: (props) => {
          return (
            <div>
             <el-button size="medium" type="text" onClick={() => this.changeManagerStatus(props.row.isLimitNum, props.row.id,1)}>
              {props.row.isLimitNum == '10041001' ? '是' : '否'}
             </el-button>
          </div>
        );
        },
      },
      {
        title: '上报时间是否可控制',
        dataIndex: 'isLimitTime',
        render: (props) => {
          return (
            <div>
            <el-button size="medium" type="text" onClick={() => this.changeManagerStatus(props.row.isLimitTime, props.row.id,2)}>
          {props.row.isLimitTime == '10041001' ? '是' : '否'}
        </el-button>
          </div>
        );
        },
      },
      {
          title: '上报金额是否可控制',
          dataIndex: 'isLimitAmount',
        render: (props) => {
          return (
            <div>
            <el-button size="medium" type="text" onClick={() => this.changeManagerStatus(props.row.isLimitAmount, props.row.id,3)}>
                   {props.row.isLimitAmount == '10041001' ? '是' : '否'}
            </el-button>
          </div>
        );
        },
        },
        {
          title: '物料组代码',
          dataIndex: 'groupCode',
          hidden:true
        }
      ];
    },
    closeDialog(){
      this.dialog.visible = false
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '备件代码',
          fieldName: 'code',
        },
        {
          type: 'INPUT',
          label: '备件名称',
          fieldName: 'partTypeName',
        }
      ];
    },
    changeManagerStatus(status, id,flag) {
      const managerstate = (status == '10041001') ? '10041002' : '10041001';
      const message = (status == '10041001') ? '否' : '是';
      this.$confirm(`确定切换为${message}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        managerStatus({ managerstate, id ,flag}).then((res) => {
          if (res.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: `操作成功!` });
            this.fetchParams = { ...this.fetchParams };
          }
        });
      });
    },
    changeHandle(val) {
      // this.fetchParams = Object.assign({}, val, { xhrAbort: false });
      const newVal = JSON.parse(JSON.stringify(val));
      this.fetchParams = Object.assign({}, newVal);
    },
    // 新增
    addhandle() {
      this.addVisible = true
    },
    // 返回
    backHandle() {
      this.isShow = false;
    },
    //单元格修改回调函数
    onCellChange(val,val2){
      var uid=Object.keys(val)[0];
      const tempObj = {};
      console.log(val2.pjlxje)
      //最低起运金额
      if(uid.split("|")[1] === 'pjlxje'){
        // console.log("你点击的是起运金额")
        tempObj.pjlxje=val2.pjlxje
        tempObj.id=val2.id
        tempObj.flag=1
        updateOrderTypeController(tempObj).then((res)=>{
          console.log(res)
          // res.data.forEach(x=>{
          //   this.columns[3].editItems.push({'text':x.seriesName,'value':x.seriesId})
          // })
        }).catch(err=>{})
      }else if(uid.split("|")[1] === 'pjlxcs'){
        console.log("你点击的是免运费次数")
        tempObj.pjlxcs=val2.pjlxcs
        tempObj.id=val2.id
        tempObj.flag=2
        //免运费次数
        updateOrderTypeController(tempObj).then((res)=>{
          console.log(res)
          // res.data.forEach(x=>{
          //   this.columns[3].editItems.push({'text':x.seriesName,'value':x.seriesId})
          // })
        }).catch(err=>{})
      }else if(uid.split("|")[1] === 'orderLimitTime'){
        console.log("你点击的是截止日期")
        tempObj.orderLimitTime=val2.orderLimitTime
        tempObj.id=val2.id
        tempObj.flag=3
        //截止日期
        updateOrderTypeController(tempObj).then((res)=>{
          console.log(res)
          // res.data.forEach(x=>{
          //   this.columns[3].editItems.push({'text':x.seriesName,'value':x.seriesId})
          // })
        }).catch(err=>{})
      }
    },
    edit(data, config) {
      this.editVisible = true
      data.flag = 2
      this.formdata = data;
    }
  },
};
</script>

<style lang="less" scoped>
    .el-checkbox + .el-checkbox {
        margin-left: 0px;
    }

    .el-checkbox {
        margin-right: 25px;
    }

    .menu-header {
        height: 30px;
        line-height: 30px;
        margin-bottom: 5px;
        background: #eee;
        text-indent: 5px;
    }
    .employeeAuthMain {
        box-sizing: border-box;
        overflow: hidden;
        .mainLeft {
            width: 25%;
            height: 100%;
            overflow-x: hidden;
            overflow-y: scroll;
            float: left;
            // padding: 10px;
            box-sizing: border-box;
        }

        .mainRight {
            width: 75%;
            height: 100%;
            overflow-x: hidden;
            overflow-y: scroll;
            float: left;
            box-sizing: border-box;
            // padding: 10px;
            border-left: 2px solid #eee;
        }
    }
</style>
